package com.pda.yuanjing.pages.xhbg;

import android.app.DatePickerDialog;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.apkfuns.logutils.LogUtils;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.pda.yuanjing.PDApp;
import com.pda.yuanjing.R;
import com.pda.yuanjing.beanin.JieDianBeanIn;
import com.pda.yuanjing.beanout.BGBeanOut;
import com.pda.yuanjing.beanout.JDBeanNewOut;
import com.pda.yuanjing.beanout.PPBeanOut;
import com.pda.yuanjing.beanout.SCBeanOut;
import com.pda.yuanjing.beanout.TJBeanOut;
import com.pda.yuanjing.boardcast.CustomReceiver;
import com.pda.yuanjing.boardcast.ScannerInterface;
import com.pda.yuanjing.dialog.product.ProductAllDialog;
import com.pda.yuanjing.dialog.product.ProductDialog;
import com.public_module.basemvp.activity.BaseActivity;
import com.public_module.config.ApiYJ;
import com.public_module.config.SetConfig;
import com.public_module.tools.DateUtils;
import com.public_module.tools.SharedPreferencesManger;
import com.public_module.tools.StringProcess;
import com.public_module.tools.ToastUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;

public class BGActivity extends BaseActivity<PageModel, PageView, PagePresent> implements PageView {
    @BindView(R.id.iv_title_left)
    ImageView ivTitleLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tvr)
    TextView tvr;
    @BindView(R.id.rltitle)
    RelativeLayout rltitle;
    @BindView(R.id.tvcp)
    TextView tvcp;
    @BindView(R.id.et)
    EditText et;
    @BindView(R.id.bt)
    Button bt;
    @BindView(R.id.tvres)
    TextView tvres;
    private String TAG = "BGActivity";
    ItemAdapter itemAdapter;
    ScannerInterface scanner;
    CustomReceiver customReceiver = null;
    ProductDialog productDialog;
    String pid = "-1";
    String pname = "";
    String pstr = "-1";
    JDBeanNewOut.DataBean dataBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bg);
        ButterKnife.bind(this);
        tvTitle.setText("型号变更 " + SharedPreferencesManger.getRealName());
        scanner = new ScannerInterface(this);
        scanner.setOutputMode(1);
        customReceiver = new CustomReceiver(
                new CustomReceiver.PListener1() {
                    @Override
                    public void setData(CustomReceiver.Dataa dataa) {
                    }
                },
                new CustomReceiver.PListener2() {
                    @Override
                    public void setText(String string) {
                        String ss = StringProcess.codeMat(string);
                        if(pstr.equals("-1")){
                            ToastUtils.showShort(BGActivity.this,"请选择产品");
                            return;
                        }
                        getRes(pstr,ss);
                    }
                });
        IntentFilter filter = new IntentFilter();
        filter.addAction(ScannerInterface.RES_ACTION);
        registerReceiver(customReceiver, filter);
        dataBean = (JDBeanNewOut.DataBean) getIntent().getSerializableExtra(PDApp.process);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (customReceiver != null) {
            unregisterReceiver(customReceiver);
        }
        if (scanner != null) {
            scanner.setOutputMode(0);
        }
    }

    @Override
    public PageModel createModel() {
        return new PageModelImpl(this);
    }

    @Override
    public PageView createView() {
        return this;
    }

    @Override
    public PagePresent createPresenter() {
        return new PagePresent();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void tip(String str) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showMsg(str);
            }
        });
    }

    @Override
    public void tipS(TJBeanOut tjBeanOut) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                itemAdapter = new ItemAdapter(BGActivity.this, tjBeanOut.getData());

            }
        });
    }

    @OnClick({R.id.iv_title_left, R.id.tvcp,  R.id.bt})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_title_left:
                finish();
                break;
            case R.id.tvcp:
                tvcp.setEnabled(false);
                presenter.initBase(pid, pname);
                productDialog = new ProductDialog(mContext, R.style.CommentDialog, new ProductDialog.PriorityListener() {
                    @Override
                    public void setActivityText(String str, String str1, int num) {
                        tvcp.setText(str);
                        pstr = str1;
                        productDialog.dismiss();
                    }
                });
                WindowManager.LayoutParams lp = productDialog.getWindow().getAttributes();
                lp.gravity = Gravity.CENTER;
                productDialog.show();
                tvcp.setEnabled(true);
                break;
            case R.id.bt:
                if(et.getText().toString().length()==0){
                    ToastUtils.showShort(this,"请输入数码");
                    return;
                }
                if(pstr.equals("-1")){
                    ToastUtils.showShort(this,"请选择产品");
                    return;
                }
                getRes(pstr,et.getText().toString());
                break;
        }
    }

    public void getRes(String id, String code) {
        try {
            showProgress();
            Gson gson = new Gson();
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(SetConfig.getConnectTimeout(), TimeUnit.SECONDS)
                    .readTimeout(SetConfig.getReadTimeout(), TimeUnit.SECONDS)
                    .writeTimeout(SetConfig.getWriteTimeout(), TimeUnit.SECONDS)
                    .followRedirects(false)
                    .build();
            ApiYJ apisync = new Retrofit.Builder()
                    .baseUrl("http://" + SharedPreferencesManger.getHostName() + "/")
                    .client(client)
                    .build().create(ApiYJ.class);

            JieDianBeanIn jieDianBeanIn = new JieDianBeanIn();
            jieDianBeanIn.setAction("SY_UpdateCode_ChangeProduct");
            jieDianBeanIn.setCid(SharedPreferencesManger.getCid());
            jieDianBeanIn.setUserID(SharedPreferencesManger.getUid());
            jieDianBeanIn.setStoreID(SharedPreferencesManger.getStoreID());
            jieDianBeanIn.setProductID(id);
            jieDianBeanIn.setCodecc(code);

            RequestBody body = RequestBody.create(SetConfig.JSON, gson.toJson(jieDianBeanIn));
            final Call<ResponseBody> call = apisync.downLoad(body);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Response<ResponseBody> response = call.execute();
                        if (response.isSuccessful()) {
                            LogUtils.e(StringProcess.responsetoString(response.body()));
                            BGBeanOut bgBeanOut = gson.fromJson(StringProcess.responsetoString(response.body()), BGBeanOut.class);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if(bgBeanOut.getErrcode()==0){
                                        String res = "";
                                        for (int i = 0; i <bgBeanOut.getData().getCodeInfo().getListResult().size() ; i++) {
                                            res = res+ bgBeanOut.getData().getCodeInfo().getListResult().get(i).getKey()+bgBeanOut.getData().getCodeInfo().getListResult().get(i).getValue() +"\n";
                                        }
                                        tvres.setText(res);
                                    }else{
                                        tvres.setText(bgBeanOut.getErrmsg());
                                    }
                                }
                            });
                        }else{
                            tvres.setText("变更失败");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                    }
                }
            });
            thread.start();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            hideProgress();
            return;
        }
    }
}
